package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.Code;
import com.itheima.domain.Result;
import com.itheima.domain.User;
import com.itheima.exception.BusinessException;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

/*@Controller
@ResponseBody*/
@RestController //上面2个注解的结合
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     *查询全部用户信息
     * @return
     *http://localhost:8080/user  get请求
     */
    @GetMapping
    public Result findAll(){
        List<User> all = userService.findAll();
//        all=null;
        return all != null ?new Result(Code.QUERY_OK,all,"查询成功"):new Result(Code.QUERY_FAIL,"查询失败");
    }

    /**
     *分页查询全部用户信息
     * @param currentPage
     * @param PageSize
     * @return
     * http://localhost:8080/user/1/5  get请求
     */
    @GetMapping("{currentPage}/{PageSize}")
    public Result findPage(@PathVariable Integer currentPage, @PathVariable Integer PageSize){
        //进行校验; 判断页数和行数不小于1; 小于则抛出异常
        if (currentPage < 1 || PageSize < 1){
            throw new BusinessException("查询的页数和条数不能小于1条");
        }

        //获取分页后的用户信息
        PageInfo<User> byPage = userService.findByPage(currentPage, PageSize);

        //将信息返回给前台页面
        return byPage != null ? new Result(Code.QUERY_OK,byPage,"查询成功") : new Result(Code.QUERY_FAIL,"查询失败");
    }

    /**
     *根据id查询用户信息
     * @param id
     * @return
     * http://localhost:8080/user/2 +get请求
     */
    @GetMapping("{id}")
    public Result findById(@PathVariable Integer id){
        User byId = userService.findById(id);
        return byId != null ? new Result(Code.QUERY_OK,byId,"查询成功") : new Result(Code.QUERY_FAIL,"查询失败");
    }

    /**
     *根据传过来的用户名和密码来查询用户信息
     * @param username
     * @param password
     * @return
     * http://localhost:8080/user/tom/123456 +post请求
     */
    @PostMapping("{username}/{password}")
    public Result findUserByUsernameAndPassword(@PathVariable String username,
                                                 @PathVariable String password,
                                                 HttpSession session){
        User usernameAndPassword = userService.findUserByUsernameAndPassword(username, password);
        if (usernameAndPassword != null){
            session.setAttribute("usernameAndPassword",usernameAndPassword);
        }
        return usernameAndPassword != null ? new Result(Code.QUERY_OK,"登录成功"):new Result(Code.QUERY_FAIL,"登录失败");
    }

    /**
     *保存用户信息
     * @param user
     * @return
     * http://localhost:8080/user +post请求
     */
    @PostMapping
    public Result save(@Validated @RequestBody User user,Errors errors){  //@Validated开启校验(修改和新增都开启校验)
        //执行操作前先校验用户信息
        errhandling(errors);
        //执行保存用户操作
        Integer save = userService.save(user);
        return save > 0 ?new Result(Code.SAVE_OK,"保存成功"):new Result(Code.SAVE_FAIL,"保存失败");
    }


    /**
     *根据id删除用户信息
     * @param id
     * @return
     * http://localhost:8080/user/6 +delete请求
     */
    @DeleteMapping("{id}")
    public Result delete(@PathVariable Integer id){
        Integer delete = userService.delete(id);
        return delete > 0 ? new Result(Code.DELETE_OK,"删除成功") : new Result(Code.DELETE_FAIL,"删除失败");
    }

    /**
     *根据id修改用户信息
     * @param user
     * @return
     * http://localhost:8080/user +put请求
     */
    @PutMapping
    public Result update(@Valid @RequestBody User user, Errors errors){ //开启校验
        //执行操作前先校验用户信息
        errhandling(errors);
        //执行保存用户操作
        Integer update = userService.update(user);
        return update > 0 ? new Result(Code.UPDATE_OK,"修改成功") : new Result(Code.UPDATE_FAIL,"修改失败");
    }

    //错误信息处理
    public void errhandling(Errors errors) {
        if (errors.hasErrors()){  //有任何错误则返回
            //获取与字段相关的所有错误, 返回错误集合
            List<FieldError> fieldErrors = errors.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                //获取字段名
                //System.out.println(fieldError.getField());
                //获取错误信息
                //System.out.println(fieldError.getDefaultMessage());
                //走到这说明有异常; 则将异常信息通过抛异常的方式交给异常处理通知类ExceptionControllerAdvice;
                //在异常处理通知类中将异常信息转换为json格式响应给客户端.
                throw new BusinessException(fieldError.getDefaultMessage());
            }
        }
    }
}
